<template>
    <div>
        <div ref="containerRef">
        </div>
        <button @click="addData">添加数据</button>
    </div>

</template>

<script setup>
import {Chart} from '@antv/g2';
import {onMounted, ref} from "vue";

const data = ref([
    {month: 'Jan', city: 'Tokyo', temperature: 7},
    {month: 'Jan', city: 'London', temperature: 3.9},
    {month: 'Feb', city: 'Tokyo', temperature: 6.9},
    {month: 'Feb', city: 'London', temperature: 4.2},
    {month: 'Mar', city: 'Tokyo', temperature: 9.5},
    {month: 'Mar', city: 'London', temperature: 5.7},
    {month: 'Apr', city: 'Tokyo', temperature: 14.5},
    {month: 'Apr', city: 'London', temperature: 8.5},
    {month: 'May', city: 'Tokyo', temperature: 18.4},
    {month: 'May', city: 'London', temperature: 11.9},
]);

const containerRef = ref(null);
const chart = ref(null);
let chart2 = null;
onMounted(() => {
    // chart.value = initChart();
    // renderChart(chart.value);
    const _chart = initChart();
    console.log('_chart',_chart)
    chart.value = _chart;
    console.log(' chart.value', chart.value)
    renderChart(_chart);

    chart2 = _chart;

    console.log('渲染了')
})
let letters = []
const addData = () => {
    const keys = ['Jan', 'Feb', 'Mar', 'Apr', 'May'];
    const childData = [];
    let city = getRandomUpperCaseLetter()
    while (letters.includes(city)) {
        city = getRandomUpperCaseLetter()
    }
    letters.push(city)

    for (let i = 0; i < keys.length; i++) {
        const key = keys[i];
        const childDataItem = {
            month: key,
            city: city,
            temperature: getRandomDouble(20, 0),
        };
        childData.push(childDataItem);
    }
    data.value = [...data.value, ...childData];
    if (chart.value) {
        console.log('data.keys',data.value.map(item => item.city))
        chart2.changeData(data.value);
    }

    // chart.value.changeData(data.value);
}
const getRandomDouble = (max,min) => {
    return Math.random() * (max - min) + min;
}
function getRandomUpperCaseLetter() {
    // 生成 65 到 90 之间的随机整数
    const randomAscii = Math.floor(Math.random() * 26) + 65;
    // 将 ASCII 码转换为对应的字符
    return String.fromCharCode(randomAscii);
}

function initChart() {
    if (!containerRef.value) {
        return;
    }
    return new Chart({
        container: containerRef.value,
        autoFit: true,
        width: 1400,
        height: 400,
    });
}

function renderChart(chart) {
    chart
        .data(data.value)
        .encode('x', 'month')
        .encode('y', 'temperature')
        .encode('color', 'city')
        .scale('x', {
            range: [0, 1],
        })
        .scale('y', {
            nice: true,
        })
        .axis('y', {labelFormatter: (d) => d + '°C'});

    chart.line().encode('shape', 'smooth');

    chart.point().encode('shape', 'point').tooltip(false);

    chart.render();
}


</script>

<style scoped>

</style>